package com.fmjava.controller;

import com.fmjava.ServiceImpl.UserServiceImpl;
import com.fmjava.domain.User;
import com.fmjava.service.UserService;
import com.sun.javaws.IconUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/ChangePasswordServlet")
public class ChangePasswordServlet extends HttpServlet {
    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         //以前的密码
         String passwordbefore=request.getParameter("passwordbefore");

         //第一次输入密码
         String password1 = request.getParameter("password1");
         //第二次输入密码
         String password2 = request.getParameter("password2");
         //获取session中当前登录用户的对象
         HttpSession session = request.getSession();
         User user =(User)session.getAttribute("user");
         //输入信息不全 提示重新输入
         if(passwordbefore.isEmpty()||password1.isEmpty()||password2.isEmpty()){
             request.setAttribute("tip","输入信息不全！");
             request.getRequestDispatcher("/WEB-INF/admin_alterPassword.jsp").forward(request,response);
         }
         //旧密码错误 提示重新输入
         else if(!passwordbefore.equals(user.getPassword())){
             request.setAttribute("tip","旧密码输入错误！");
             request.getRequestDispatcher("/WEB-INF/admin_alterPassword.jsp").forward(request,response);
         }//两次密码输入不一致 提示重新输入
         else if(!password1.equals(password2)){
             request.setAttribute("tip","两次密码输入不一致！");
             request.getRequestDispatcher("/WEB-INF/admin_alterPassword.jsp").forward(request,response);
         }//新密码与旧密码相同 提示重新输入
         else if(password1.equals(passwordbefore)){
             request.setAttribute("tip","新密码与旧密码相同！");
             request.getRequestDispatcher("/WEB-INF/admin_alterPassword.jsp").forward(request,response);
         }else{
             UserService userService=new UserServiceImpl();
             userService.updateUser(user,password1);
             session.invalidate();
             response.sendRedirect("/admin_login.jsp");
         }

    }
}
